#include <stdio.h>
#include <math.h>

//编译：g++ -o run_fit_curve fit_curve.c

// 函数声明
void gaussianElimination(double matrix[3][4], int n);

int main() {
    double points[3][2] = {
        {12895.000000, 3.778000}, // 点1
        {32614.000000, 9.361000}, // 点2
        {22871.000000, 6.402000}  // 点3
    };
    double matrix[3][4];

    // 构建增广矩阵
    for (int i = 0; i < 3; i++) {
        matrix[i][0] = points[i][0] * points[i][0];
        matrix[i][1] = points[i][0];
        matrix[i][2] = 1;
        matrix[i][3] = points[i][1];
    }

    // 调用高斯消元法函数
    gaussianElimination(matrix, 3);

    // 输出结果
    printf("The equation of the parabola is: \n");
    printf("y = %lfx^2 + %lfx + %lf\n", matrix[0][3], matrix[1][3], matrix[2][3]);

    float x[10] = {1328,2465,3606,4742,7012,8146,9276,10406,11536,12663};
    for (size_t i = 0; i < 10; i++)
    {
        printf("x=%f so y=%f \r\n",x[i],(matrix[0][3]*pow(x[i],2))+(matrix[1][3]*x[i])+matrix[2][3]);
    }

    

    return 0;
}

// 高斯消元法函数
void gaussianElimination(double matrix[3][4], int n) {
    double factor;
    for (int k = 0; k < n - 1; k++) {
        for (int i = k + 1; i < n; i++) {
            factor = matrix[i][k] / matrix[k][k];
            for (int j = k; j <= n; j++) {
                matrix[i][j] -= factor * matrix[k][j];
            }
        }
    }

    // 回代求解
    for (int i = n - 1; i >= 0; i--) {
        for (int j = i + 1; j < n; j++) {
            matrix[i][n] -= matrix[j][n] * matrix[i][j];
        }
        matrix[i][n] /= matrix[i][i];
    }
}